package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FOLLOW;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IUserService userService;

    /**
     * 关注或者取关用户
     *
     * @param followUserId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        // 1、获取当前用户id
        Long userId = UserHolder.getUser().getId();
        // 2、判断是关注还是取关
        Follow follow = null;
        // 2.1、到数据库查找用户对该用户的关注数据，判断是否已经关注
        Map sqlParam = new HashMap<>(2);
        sqlParam.put("user_id", userId);
        sqlParam.put("follow_user_id", followUserId);
        QueryWrapper queryWrapper = new QueryWrapper<Follow>().allEq(sqlParam);
        follow = this.getOne(queryWrapper);
        // 2.2、保存用户关注的id的key
        String key = FOLLOW + userId;
        if (BooleanUtil.isTrue(isFollow)) {
            // 没关注过，添加关注
            if (follow == null) {
                follow = new Follow();
                follow.setFollowUserId(followUserId);
                follow.setUserId(userId);
                boolean isSuccess = this.save(follow);
                if (isSuccess) {
                    // 将该用户关注的用户id放到redis的set里
                    stringRedisTemplate.opsForSet().add(key, followUserId.toString());
                }
            } else {
                // 2.2、取关
                if (follow != null) {
                    boolean isSuccess = this.remove(queryWrapper);
                    // 同时删掉redis里的id
                    if (isSuccess) {
                        stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
                    }
                }
            }
        }
        return Result.ok();
    }

    /**
     * 查询用户是否关注与否
     *
     * @param followUserId
     * @return
     */
    @Override
    public Result isFollow(Long followUserId) {
        // 1、获取用户id
        Long userId = UserHolder.getUser().getId();
        // 2、查看是否关注了
        int count = this.count(new QueryWrapper<Follow>().eq("user_id", userId).eq("follow_user_id", followUserId));
        return Result.ok(count > 0);
    }

    /**
     * 共同关注
     * @param id
     * @return
     */
    @Override
    public Result commonFollow(Long id) {
        // 1、获取当前用户的id
        Long userId = UserHolder.getUser().getId();
        // 2、获取当前用户和该用户的共同关注id，借助redis的sinter命令，获取两个set的交集
        String userKey = FOLLOW + userId;
        String followKey = FOLLOW + id;
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(userKey, followKey);
        // 3、没有共同关注
        if (intersect.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        // 4、转换成Long
        List<Long> idList = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        // 5、查找这些共同id的信息
        List<User> userList = userService.listByIds(idList);
        return Result.ok(BeanUtil.copyToList(userList, UserDTO.class));
    }


}
